package team.archai.nexus.flow.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;

import java.util.*;

/**
 * @program: flow
 * @description: 排除act 自动配置如果未开启流程
 * @author: lishibin
 * @create: 2024-04-01
 **/
public class ExcludeEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {


    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String key = "spring.autoconfigure.exclude";
        Binder binder = Binder.get(environment);
        // 1 先获取到原配置文件的信息。这里参考的AutoConfigurationImportSelector#getExcludeAutoConfigurationsProperty
        List<String> stringList = binder.bind(key, String[].class).map(Arrays::asList).orElse(Collections.emptyList());
        List<String> exList = new ArrayList<>(stringList);
        String flowEnabled = environment.getProperty("archai-nexus.flow-designer.enabled");
        if (!Boolean.TRUE.toString().equals(flowEnabled)) {
            // 2 增加需要排除的类
            exList.add("org.activiti.spring.boot.ProcessEngineAutoConfiguration");
            exList.add("org.activiti.spring.process.conf.ProcessExtensionsAutoConfiguration");
            exList.add("org.activiti.runtime.api.conf.ConnectorsAutoConfiguration");
            exList.add("org.activiti.spring.process.conf.ProcessExtensionsConfiguratorAutoConfiguration");
            exList.add("org.activiti.runtime.api.conf.ProcessRuntimeAutoConfiguration");
            exList.add("org.activiti.spring.boot.EndpointAutoConfiguration");
            exList.add("org.activiti.application.conf.ApplicationProcessAutoConfiguration");
            exList.add("org.activiti.runtime.api.conf.CommonRuntimeAutoConfiguration");
            exList.add("org.activiti.runtime.api.conf.TaskRuntimeAutoConfiguration");
            //自定义的类排除
        }
        MutablePropertySources m = environment.getPropertySources();
        Properties p = new Properties();
        p.put(key, String.join(",", exList));
        // 3 保存新的配置文件
        m.addFirst(new PropertiesPropertySource("spring-exclude-flow-designer", p));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
